package com.wnxy.admin.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wnxy.admin.common.ResponseResult;
import com.wnxy.admin.common.handler.BusinessEnum;
import com.wnxy.admin.common.handler.GlobalVariable;
import com.wnxy.admin.common.util.AlyOssUtil;
import com.wnxy.admin.entity.CarImage;
import com.wnxy.admin.service.ICarImageService;
import com.wnxy.admin.service.ICarService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import static com.google.common.io.Files.getFileExtension;

/**
 * <p>
 * 车辆图片表 前端控制器d
 * </p>
 *
 * @author LQC
 * @since 2023-11-29
 */
@RestController
@RequestMapping("/car-image")
public class CarImageController {

    private final ICarImageService carImageServiceImpl;
    private final ICarService carServiceImpl;

    public CarImageController(ICarImageService carImageServiceImpl, ICarService carServiceImpl) {
        this.carImageServiceImpl = carImageServiceImpl;
        this.carServiceImpl = carServiceImpl;
    }

    //根据车牌号显示查询车辆图片
    @GetMapping("/getImg/{carNum}")
    public ResponseResult getImgByCarNum(@PathVariable String carNum) {
        List<CarImage> images = carImageServiceImpl.list(Wrappers.lambdaQuery(CarImage.class)
                .eq(CarImage::getCarNum, carNum));
        return ResponseResult.ok(images);
    }


    //------上传图片
    @PostMapping("/upload")
    public ResponseResult handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseResult.fail(BusinessEnum.CARNUM_OR_CARVIM_REPEAT);
        }

        try {
            // 在这里可以添加处理上传文件的逻辑，例如保存文件信息到数据库
            String uuid = String.valueOf(UUID.randomUUID());
            uuid = uuid.replace("-", "");
            String fileName = uuid + "." + getFileExtension(file.getOriginalFilename());

            // 上传文件到阿里云 OSS
            InputStream inputStream = file.getInputStream();
            String ossUrl = AlyOssUtil.uploadFile(fileName, inputStream);

            // 在这里可以添加保存文件信息到数据库的逻辑
            CarImage carImage = new CarImage();
            carImage.setCarNum(GlobalVariable.CAR_NUM);
            carImage.setImageSrc(ossUrl);
            carImageServiceImpl.save(carImage);

            return ResponseResult.ok();
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.fail(BusinessEnum.CARNUM_OR_CARVIM_REPEAT);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(BusinessEnum.CARNUM_OR_CARVIM_REPEAT);
        }
    }

    @PostMapping("/change")
    public ResponseResult handleFileChange(@RequestParam("file") MultipartFile file, String carNum) {
        try {
            if (file.isEmpty()) {
                return ResponseResult.fail(BusinessEnum.CARNUM_OR_CARVIM_REPEAT);
            }
            List<CarImage> carImages = carImageServiceImpl.list(Wrappers.lambdaQuery(CarImage.class)
                    .eq(CarImage::getCarNum, carNum));

            // 生成新的文件名
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String fileName = uuid + "." + getFileExtension(file.getOriginalFilename());

            // 上传文件到阿里云 OSS
            InputStream inputStream = file.getInputStream();
            String ossUrl = AlyOssUtil.uploadFile(fileName, inputStream);

            // 删除原有的文件和数据库记录

            if (!carImages.isEmpty()) {
                carImageServiceImpl.remove(Wrappers.lambdaQuery(CarImage.class)
                        .eq(CarImage::getCarNum, carNum));

                for (CarImage existingCarImage : carImages) {
                    String existingFileName = AlyOssUtil.extractFileName(existingCarImage.getImageSrc());
                    AlyOssUtil.delete(existingFileName);
                }
                // 删除数据库记录
            }

            // 保存新的数据库记录
            CarImage carImage = new CarImage();
            carImage.setCarNum(carNum);
            carImage.setImageSrc(ossUrl);
            carImageServiceImpl.save(carImage);

            return ResponseResult.ok();
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.fail(BusinessEnum.CARNUM_OR_CARVIM_REPEAT);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(BusinessEnum.CARNUM_OR_CARVIM_REPEAT);
        }
    }
}
